<template>
  <div class="echarts-container">
    <!-- 业务整体入组情况 -->
    <div class="chart-container">
      <div class="chart-title">
        <Histogram style="width: 18px; height: 18px" />
        <span>业务整体入组情况</span>
      </div>
      <div
        :ref="el => setChartRef(el, index)"
        :id="`chart-${index}`"
        class="chart"
        style="width: 50%; height: 220px"
        v-for="(item, index) in groupChartList"
        :key="item"
      ></div>
    </div>
    <!-- 各中心分组性别对比 -->
    <div class="chart-container">
      <div class="chart-title">
        <Histogram style="width: 18px; height: 18px" />
        <span>各分组性别对比</span>
      </div>
      <div ref="setChartRefXB" class="chart"></div>
    </div>
    <!-- 各中心入组情况对比 -->
    <div class="chart-container">
      <div class="chart-title">
        <Histogram style="width: 18px; height: 18px" />
        <span>各中心入组情况</span>
      </div>
      <div ref="setChartRefRZ" class="chart"></div>
    </div>
    <!-- 各中心入组情况对比 -->
    <div class="chart-container">
      <div class="chart-title">
        <Histogram style="width: 18px; height: 18px" />
        <span>各中心入组分布情况</span>
      </div>
      <div ref="setChartRefFB" class="chart"></div>
    </div>
    <!-- 各分组年龄分布情况---饼图 -->
    <div class="chart-container" style="width: 100%; height: auto; min-height: 500px">
      <div class="chart-title">
        <Histogram style="width: 18px; height: 18px" />
        <span>各分组年龄分布情况</span>
      </div>
      <div
        :ref="el => setChartRef2(el, index)"
        class="chart"
        style="width: 50%; height: 500px"
        v-for="(item, index) in pieChartList"
        :key="index"
      ></div>
    </div>
  </div>
</template>
<script setup>
import { overall, numWithAgeGroup, numWithGroupDept, groupSex, deptSex } from '@/api/trial/trial';
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import * as echarts from 'echarts';
const route = useRoute();
const router = useRouter();
const crud = ref(null);
const store = useStore();
const routerQuery = ref({});
routerQuery.value = route.query;

const props = defineProps({
  sendTrialVal: {
    type: Object,
    default: {},
  },
});

let groupChartList = ref([
  {
    title: '总入组情况',
  },
  {
    title: '各分组对比',
  },
  {
    title: '总性别对比',
  },
  {
    title: '总年龄对比',
  },
]);
let pieChartList = ref([]);

// 存储图表实例和 DOM 引用的响应式数组
const chartRefs = ref([]);
const chartInstances = ref([]);

// 动态绑定 ref 的方法
const setChartRef = (el, index) => {
  chartRefs.value[index] = el;
};

// 存储图表实例和 DOM 引用的响应式数组
const chartRefs2 = ref([]);
const chartInstances2 = ref([]);

// 动态绑定 ref 的方法
const setChartRef2 = (el, index) => {
  chartRefs2.value[index] = el;
};
let setChartRefXB = ref(null);
let chartInstanceXB = null;

let setChartRefRZ = ref(null);
let chartInstanceRZ = null;

let setChartRefFB = ref(null);
let chartInstanceFB = null;
// 初始化图表
const initChart = () => {
  overall(props.sendTrialVal.id).then(res => {
    const DATA = res.data.data;
    // let dataName = {
    //   0: ['入组数', '脱落数'],
    //   2: ['男', '女'],
    //   3: ['儿童数', '少年数', '青年数', '中年数', '老年数', 'missing'],
    // };
    let axiosMap = {
      0: 'tuoluoMap',
      1: 'groupNumMap',
      2: 'sexNumMap',
      3: 'ageNumMap',
    };
    let axiosMapData = {
      0: [DATA[axiosMap[0]].total, DATA[axiosMap[0]].tuoluo],
      1: DATA[axiosMap[1]].groupNumList,
      2: [DATA[axiosMap[2]].nan, DATA[axiosMap[2]].nv],
      3: DATA[axiosMap[3]].ageNum,
    };
    let dataName = {
      0: ['入组数', '脱落数'],
      2: ['男', '女'],
      3: DATA[axiosMap[3]].ageTypeStr,
    };
    let xName = {
      0: ['整体入组情况：脱落'],
      1: DATA[axiosMap[1]].groupNameList,
      2: ['整体入组情况：性别'],
      3: ['整体入组情况：年龄'],
    };
    chartInstances.value = chartRefs.value.map((el, index) => {
      let seriesData = [];
      if (!el) return null;

      if (index === 1) {
        seriesData = [
          {
            data: axiosMapData[index],
            type: 'bar',
            barWidth: 20, // 设置柱子的宽度
          },
        ];
      } else {
        dataName[index].forEach((item, i) => {
          seriesData.push({
            name: item,
            data: [axiosMapData[index][i]],
            type: 'bar',
            barWidth: 20, // 设置柱子的宽度
          });
        });
      }

      // 创建图表实例
      const chart = echarts.init(el);

      // 示例配置（可根据不同索引设置不同配置）
      chart.setOption({
        title: {
          text: groupChartList.value[index].title,
          left: 'left',
          textStyle: {
            color: 'black',
            fontSize: 14,
          },
        },
        grid: { left: '10', right: '10', bottom: '50', top: '50', containLabel: true },
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'cross' },
        },
        legend: {
          top: '0',
          orient: 'vertical', // 设置为垂直布局
          left: 'right', // 可以放置在图表的右侧
          // top: 'middle', // 垂直居中
          textStyle: {
            color: 'black',
            fontSize: 12,
          },
          data: dataName[index],
        },
        xAxis: {
          type: 'category',
          data: xName[index], // 将你的长文本放在 data 数组中
          axisLabel: {
            interval: 0, // 强制显示所有标签
            // rotate: 30, // 如果文字很长，可以通过旋转角度来避免重叠
            formatter: function (value) {
              return value; // 你可以进一步定制格式化输出
            },
          },
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value} 人', // 每个数值后加上"人"单位
          },
        },
        series: seriesData,
      });

      return chart;
    });
  });
};

const initChartXB = () => {
  groupSex(props.sendTrialVal.id).then(res => {
    const DATA = res.data.data;
    const dataName = ['入组数', '男', '女', '脱落数'];
    let xName = Object.keys(DATA);
    const seriesData = ['total', 'nan', 'nv', 'tuoluo'].map((key, index) => ({
      name: dataName[index],
      type: 'bar',
      data: Object.values(DATA).map(item => item[key]),
    }));
    chartInstanceXB = echarts.init(setChartRefXB.value);
    let option = {
      title: {
        text: '各分组性别对比',
        left: 'left',
        textStyle: { color: 'black', fontSize: 14 },
      },
      grid: { left: '10', right: '10', bottom: '50', top: '50', containLabel: true },
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'cross' },
      },
      legend: {
        top: '0',
        orient: 'vertical',
        left: 'right',
        textStyle: { color: 'black', fontSize: 12 },
        data: dataName,
      },
      xAxis: {
        type: 'category',
        data: xName,
        axisLabel: { interval: 0, formatter: value => value },
      },
      yAxis: {
        type: 'value',
        axisLabel: { formatter: '{value} 人' },
      },
      series: seriesData,
    };
    chartInstanceXB.setOption(option);
  });
};
const initChartRZ = () => {
  deptSex(props.sendTrialVal.id).then(res => {
    const DATA = res.data.data;
    const dataName = ['入组数', '男', '女', '脱落数'];
    let xName = Object.keys(DATA);
    const seriesData = ['total', 'nan', 'nv', 'tuoluo'].map((key, index) => ({
      name: dataName[index],
      type: 'bar',
      data: Object.values(DATA).map(item => item[key]),
    }));
    chartInstanceRZ = echarts.init(setChartRefRZ.value);
    let option = {
      title: {
        text: '各中心入组情况',
        left: 'left',
        textStyle: { color: 'black', fontSize: 14 },
      },
      grid: { left: '10', right: '10', bottom: '50', top: '50', containLabel: true },
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'cross' },
      },
      legend: {
        top: '0',
        orient: 'vertical',
        left: 'right',
        textStyle: { color: 'black', fontSize: 12 },
        data: dataName,
      },
      xAxis: {
        type: 'category',
        data: xName,
        axisLabel: { interval: 0, formatter: value => value },
      },
      yAxis: {
        type: 'value',
        axisLabel: { formatter: '{value} 人' },
      },
      series: seriesData,
    };
    chartInstanceRZ.setOption(option);
  });
};
const initChartFB = () => {
  numWithGroupDept(props.sendTrialVal.id).then(res => {
    const DATA = res.data.data;
    let dataName = [];
    let xName = [];
    let result = [];
    // 通过 map 来简化数据处理
    DATA.forEach(item => {
      item.groupName.forEach((group, index) => {
        let existing = result.find(r => r.name === group);
        if (existing) {
          existing.data.push(item.num[index]);
        } else {
          result.push({
            name: group,
            type: 'bar',
            data: [item.num[index]],
            barWidth: 20,
          });
        }
      });
    });

    // 更新 dataName 和 xName 的值
    dataName = DATA.flatMap(item => item.groupName);
    xName = DATA.map(item => item.deptName);

    chartInstanceFB = echarts.init(setChartRefFB.value);
    let option = {
      title: {
        text: '各中心入组情况',
        left: 'left',
        textStyle: { color: 'black', fontSize: 14 },
      },
      grid: { left: '10', right: '10', bottom: '50', top: '50', containLabel: true },
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'cross' },
      },
      legend: {
        top: '0',
        orient: 'vertical',
        left: 'right',
        textStyle: { color: 'black', fontSize: 12 },
        data: dataName,
      },
      xAxis: {
        type: 'category',
        data: xName,
        axisLabel: { interval: 0, formatter: value => value },
      },
      yAxis: {
        type: 'value',
        axisLabel: { formatter: '{value} 人' },
      },
      series: result,
    };
    chartInstanceFB.setOption(option);
  });
};
// 初始化图表
const initChart1 = () => {
  let dataName = [
    ['入组数', '男', '女', '脱落数'],
    ['入组数', '男', '女', '脱落数'],
  ];
  let xName = [['研究组', '测试组'], ['中国科学技术大学附属第一医院']];
  let result = [];
  numWithGroupDept(props.sendTrialVal.id).then(res => {
    const DATA = res.data.data;

    // 通过 map 来简化数据处理
    DATA.forEach(item => {
      item.groupName.forEach((group, index) => {
        let existing = result.find(r => r.name === group);
        if (existing) {
          existing.data.push(item.num[index]);
        } else {
          result.push({
            name: group,
            type: 'bar',
            data: [item.num[index]],
            barWidth: 20,
          });
        }
      });
    });

    // 更新 dataName 和 xName 的值
    dataName[2] = DATA.flatMap(item => item.groupName);
    xName[2] = DATA.map(item => item.deptName);

    console.log(dataName, xName);

    // 更新图表实例
    chartInstances1.value = chartRefs1.value.map((el, index) => {
      if (!el) return null;

      const seriesData =
        index === 2
          ? result
          : dataName[index].map(item => ({
              name: item,
              data: [Math.random() * 300, Math.random() * 400],
              type: 'bar',
              barWidth: 20,
            }));

      // 创建图表实例
      const chart = echarts.init(el);
      chart.setOption({
        title: {
          text: elseChartList.value[index].title,
          left: 'left',
          textStyle: { color: 'black', fontSize: 14 },
        },
        grid: { left: '10', right: '10', bottom: '50', top: '50', containLabel: true },
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'cross' },
        },
        legend: {
          top: '0',
          orient: 'vertical',
          left: 'right',
          textStyle: { color: 'black', fontSize: 12 },
          data: dataName[index],
        },
        xAxis: {
          type: 'category',
          data: xName[index],
          axisLabel: { interval: 0, formatter: value => value },
        },
        yAxis: {
          type: 'value',
          axisLabel: { formatter: '{value} 人' },
        },
        series: seriesData,
      });

      return chart;
    });
  });
};

const initChart2 = () => {
  pieChartList.value = [];
  let dataName = [];
  numWithAgeGroup(props.sendTrialVal.id).then(res => {
    const DATA = res.data.data;
    DATA.forEach(item => {
      pieChartList.value.push({
        title: item.groupName,
      });
      dataName.push(item.ageTypeStr);
    });
    // let dataName = {
    //   0: ['儿童数', '少年数', '青年数', '中年数', '老年数'],
    //   1: ['儿童数', '少年数', '青年数', '中年数', '老年数'],
    // };
    setTimeout(() => {
      chartInstances2.value = chartRefs2.value.map((el, index) => {
        let seriesData = [];
        if (!el) return null;

        dataName[index].forEach((item, i) => {
          seriesData.push({
            value: DATA[index].ageNum[i],
            name: item,
          });
        });
        // 创建图表实例
        const chart = echarts.init(el);

        // 示例配置（可根据不同索引设置不同配置）
        chart.setOption({
          title: {
            text: pieChartList.value[index].title,
            left: 'left',
            textStyle: {
              color: 'black',
              fontSize: 14,
            },
          },
          tooltip: {
            trigger: 'item',
          },
          legend: {
            top: '0',
            orient: 'vertical', // 设置为垂直布局
            left: 'right', // 可以放置在图表的右侧
            // top: 'middle', // 垂直居中
            textStyle: {
              color: 'black',
              fontSize: 12,
            },
            data: dataName[index],
          },
          series: [
            {
              radius: '50%',
              data: seriesData,
              type: 'pie',
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)',
                },
              },
            },
          ],
        });

        return chart;
      });
    }, 1000);
  });
};
let resizeHandler = ref(null);
onMounted(() => {
  nextTick(() => {
    initChart();
    // initChart1();
    initChart2();
    initChartXB();
    initChartRZ();
    initChartFB();
    // 事件处理函数保存到变量中
    resizeHandler = () => {
      chartInstances.value.forEach(chart => chart?.resize());
    };

    // 添加窗口resize监听
    window.addEventListener('resize', resizeHandler);
  });
});
// 组件卸载时清理
onBeforeUnmount(() => {
  chartInstances.value.forEach(chart => chart?.dispose());
  // 移除事件监听时传递相同的事件处理函数
  window.removeEventListener('resize', resizeHandler);
});
</script>
<style scoped>
.echarts-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
.chart-container {
  width: 50%;
  height: 500px;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
.chart-title {
  width: 100%;
  height: 30px;
  font-size: 18px;
  color: black;
  display: flex;
  align-items: center;
}
.chart {
  width: 100%;
  height: 100%;
}
</style>